

package com.timber.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;


/**
 * Collection of utility methods to manipulate with SLDataObject
 * collections.
 */
public final class ObjectUtil {
    /**
     * Returns union of two sets.
     */
    public final static List union(List arg1, List arg2) {
        throw new Error("method is not implemented yet");
    }

    /**
     * Returns arg1 - arg2
     */
    public final static List subtraction(List arg1, List arg2) {
        HashSet set = new HashSet(arg2.size());
        for (Iterator i = arg2.iterator(); i.hasNext();) {
            set.add(new Long(((SLDataObject) i.next()).getId()));
        }
        ArrayList ret = new ArrayList(arg1.size());
        for (Iterator i = arg1.iterator(); i.hasNext();) {
            SLDataObject obj = (SLDataObject) i.next();
            if (!set.contains(new Long(obj.getId()))) {
                ret.add(obj);
            }
        }
        return ret;
    }
    
    /**
     * Reads an object from 
     * a serialsed object file.
     * @param fileName
     * @return
     */
    public final static Object readObjectFromFile(String fileName){
    	Object object = null;
    	File serialisedObject = new File(fileName);
		 if (serialisedObject.exists()){
			 try {
				FileInputStream fInput = new FileInputStream(serialisedObject);
				 ObjectInputStream oIn = new ObjectInputStream(fInput);
				 object = oIn.readObject();
				 oIn.close();
			} catch (Exception e) {
				Util.log("Unable to read object from serialised file " + fileName);
			}
		 }
		 return object;
    }
    
    /**
     * Writes an object to a file.
     * @param object
     * @param fileName
     */
    public static final void writeObjectToFile(Serializable object, String fileName){
    	try {
			FileOutputStream fout = new FileOutputStream(fileName);
			 ObjectOutputStream oOut = new ObjectOutputStream(fout);
			 oOut.writeObject(object);
			 oOut.close();
		} catch (Exception e) {
			Util.log("Unable to serialse object to  file " + fileName);
		}
    }
}
